package org.jeecg.modules.villageCadreAssist.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.jeecg.modules.villageCadreAssist.entity.VcaEducation;
import org.jeecg.modules.villageCadreAssist.entity.VcaResident;
import org.jeecg.modules.villageCadreAssist.mapper.VcaEducationMapper;
import org.jeecg.modules.villageCadreAssist.service.IVcaEducationService;
import org.jeecg.modules.villageCadreAssist.service.IVcaResidentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description: vca_education
 * @Author: jeecg-boot
 * @Date:   2022-02-28
 * @Version: V1.0
 */
@Service
public class VcaEducationServiceImpl extends ServiceImpl<VcaEducationMapper, VcaEducation> implements IVcaEducationService {

    @Autowired
    private IVcaResidentService vcaResidentService;

    @Override
    public IPage<VcaEducation> queryPageList(Page<VcaEducation> page, QueryWrapper<VcaEducation> queryWrapper,String orgCode) {
        return baseMapper.queryPageList(page,queryWrapper,orgCode);
    }

    @Override
    @Transactional
    public void saveExcelBatch(List<VcaEducation> list) {
        int batchNum = 500;
        List<VcaEducation> batchList = new ArrayList<>(batchNum);
        for (int i = 0; i < list.size(); i++) {
            batchList.add(list.get(i));
            if(i%batchNum==0 && i != 0){
                doSaveExcelBatch(batchList);
                batchList.clear();
            }
        }
        if(batchList.size()>0){
            doSaveExcelBatch(batchList);
        }
    }

    private void doSaveExcelBatch(List<VcaEducation> list){
        List<VcaResident> residentList = vcaResidentService.list(new LambdaQueryWrapper<VcaResident>()
                .in(VcaResident::getIdcard, list.stream().map(item -> item.getIdcard())));
        Map<String, Integer> idMap = residentList.stream().collect(Collectors.toMap(VcaResident::getIdcard, VcaResident::getId));
        list.forEach(item->{
            item.setResidentId(idMap.get(item.getIdcard()));
        });
        super.saveBatch(list);
    }

}
